package com.invengo.base.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class CompressUtil {
    public static String compresss(String str){
        if (str == null || str.length() == 0) {
            return str;
        }
        String outStr = "";
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes());
            gzip.close();
            outStr = Base64Util.encode(out.toByteArray());
        }catch (Exception e){
            e.printStackTrace();
        }
        return outStr;
    }


    public static void decompresss(StringBuilder stringBuilder,String encodedContent) throws IOException {
        if (encodedContent == null || encodedContent.length() == 0) {
            return;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(Base64Util.decode(encodedContent)));
            String outStr = "";
            byte[] buffer = new byte[256];
            int n;
            while ((n = gis.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        stringBuilder.append(out.toByteArray());
        out.close();
    }

    public static String decompresss(String encodedContent) {
        if (encodedContent == null || encodedContent.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(Base64Util.decode(encodedContent)));
            byte[] buffer = new byte[256];
            int n;
            while ((n = gis.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        String outStr = out.toString();
        try{
            out.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return  outStr;
    }
}
